import 'dart:async';

import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:photo_frame/net/http_manager.dart';
import 'package:photo_frame/push/FCM.dart';
import 'package:photo_frame/utils/a_logger.dart';
import 'package:photo_frame/utils/global_shared_preferences.dart';

import '../router/router_context.dart';

class UserManager {
  static UserManager instance = UserManager._();
  late UserInfo _userInfo;

  UserManager._();
  init() async {
    _userInfo = UserInfo();
    _userInfo._token = GlobalSharedPreferences.instance.sp.getString("token");
  }

  isLoggedIn() {
    return _userInfo._token != null && _userInfo._token?.isNotEmpty == true;
  }

  getId() {
    return _userInfo.id;
  }

  getToken() {
    return _userInfo._token;
  }

  String? getAvatar() {
    return _userInfo._url;
  }

  String? getEmail() {
    return _userInfo._email;
  }

  int? getAvatarColor() {
    return _userInfo._avatarColor;
  }

  String? getName() {
    return _userInfo._name;
  }

  saveUserInfo(Map<String, dynamic>? data) {
    _userInfo.id = data?["id"];
    _userInfo._avatarColor = data?["color"];
    _userInfo._name = data?["name"];
    _userInfo._url = data?["url"];
    _userInfo._email = data?["email"];
  }

  login(String? token) async {
    if (token == null || token.isEmpty) {
      return;
    }
    _userInfo._token = token;
    FCM().bindToken();
    await GlobalSharedPreferences.instance.sp.setString("token", token);
  }

  logout() async {
    _userInfo._token = null;
    await GlobalSharedPreferences.instance.sp.clear();
    ARouter.instance.logout();
  }

  syncUserInfo() async {
    final response = await HttpManager.instance.doRequest("/info/userinfo");
    if (!response.isSuccess) {
      return;
    }
    UserManager.instance.saveUserInfo(response.data);
  }
}

class UserInfo {
  num? id;

  String? _token;

  String? _name;

  String? _email;

  int? _avatarColor;

  String? _url;
}
